package com.rzjm.api.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.Security;

/**
 * @创建者：zhouwei
 * @创建时间：2024-05-21
 * @描述：
 */
public class Sm4Utils {

    public static final String ALGORITHM_NAME = "SM4";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * SM4加密
     * @param secretKeyHex 秘钥
     * @param plaintext 明文字符串
     * @return 加密后的密文（字节数组）
     * @throws Exception 加密过程中的异常
     */
    public static byte[] encrypt(String secretKeyHex, String plaintext) throws Exception {
        byte[] secretKey = Sm4Utils.hexStrToBytes(secretKeyHex);

        Key secretKey1 = new SecretKeySpec(secretKey,ALGORITHM_NAME);
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey1);

        return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * SM4解密
     *
     * @param secretKey 秘钥
     * @param ciphertext 密文（字节数组）
     * @return 解密后的明文字符串
     * @throws Exception 解密过程中的异常
     */
    public static String decrypt(byte[] secretKey,byte[] ciphertext) throws Exception {
        Key secretKey1 = new SecretKeySpec(secretKey, ALGORITHM_NAME);
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME, "BC");
        cipher.init(Cipher.DECRYPT_MODE, secretKey1);

        return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
    }

    /**
     * 将字节数组转换为十六进制字符串
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 将16进制字符串转为byte
     * @param hexStr
     * @return
     */
    public static byte[] hexStrToBytes(String hexStr) {
        String t = hexStr;
        if (t.length() % 2 == 1) {
            t = "0" + hexStr;
        }
        byte[] bytes = new byte[t.length() / 2];
        for (int i = 0; i < t.length(); i += 2) {
            bytes[i / 2] = (byte) Integer.parseInt(t.substring(i, i + 2), 16);
        }
        return bytes;
    }


    public static void main(String[] args) {

        final String secretKeyHex = "18a5e14c665b46a197c645975bbd1ebf";

        try {
            byte[] secretKey = Sm4Utils.hexStrToBytes(secretKeyHex);

            String plaintext = "你好，你好，你好，你好，你好，你好，你好";
            System.out.println("加密前: " + plaintext);

            // 加密
            byte[] encrypted = Sm4Utils.encrypt(secretKeyHex,plaintext);
            System.out.println("加密后: " + Sm4Utils.bytesToHex(encrypted));

            // 解密
            String decrypted = Sm4Utils.decrypt(secretKey,encrypted);
            System.out.println("解密后: " + decrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
